package com.szholly.data.general;

import java.util.HashMap;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.szholly.data.cache.MetadataDataCache;
import com.szholly.data.general.configuration.DefulatConfig;

/**
 * 定义工作空间工厂类 2014.6.4
 */
@Component("WorkspaceFactory")
public class WorkspaceFactoryClass implements IWorkspaceFactory,
		BeanFactoryAware {

	@Autowired
	private BeanFactory objectFactory;

	@Autowired
	private DefulatConfig defulatConfig;

	/**
	 * Spring注放Bean工厂
	 */
	public void setBeanFactory(BeanFactory value) {
		objectFactory = value;
	}

	/**
	 * 创建工作空间，根据配置节名称
	 */
	@Override
	public IWorkspace openWorkspace() {
		// 解析连接信息
		ConnectionInfo info = new ConnectionInfo("", null);
		info.setDatabase(defulatConfig.getDatabase());
		info.setNetName(defulatConfig.getNetName());
		info.setPassword(defulatConfig.getPassword());
		info.setPort(defulatConfig.getPort());
		info.setServer(defulatConfig.getServer());
		info.setUserID(defulatConfig.getUserID());
		info.setVersion(defulatConfig.getVersion());
		info.setWorkspaceType(WorkspaceType
				.getWorkspaceTypeByTypeId(defulatConfig.getDbProvideType()));
		return openDbWorkspace(info);
	}

	/**
	 * 创建工作空间，根据给定的工作空间信息
	 */
	@Override
	public IWorkspace openDbWorkspace(ConnectionInfo info) {
		if (info == null)
			return null;

		String key = info.getConnectionStr() + "_" + info.getWorkspaceType().toString() + "_DB";
		HashMap<String, IWorkspace> workspaceCache = MetadataDataCache.getWorkspaceCache();
		if (workspaceCache.containsKey(key)) {
			return workspaceCache.get(key);
		} else {
			String objName = "Workspace_DB_"
					+ info.getWorkspaceType().toString();
			IWorkspace adoWorkspace = (IWorkspace) (objectFactory.getBean(
					objName, new Object[] { info }));
			workspaceCache.put(key, adoWorkspace);
			return adoWorkspace;
		}
	}

	/**
	 * 创建工作空间，根据给定的工作空间信息
	 */
	@Override
	public IWorkspace openUrlWorkspace(ConnectionInfo info) {
		if (info == null)
			return null;

		String key = info.getConnectionStr() + "_"
				+ info.getWorkspaceType().toString() + "_URL";
		HashMap<String, IWorkspace> workspaceCache = MetadataDataCache.getWorkspaceCache();
		if (workspaceCache.containsKey(key)) {
			return workspaceCache.get(key);
		} else {
			String objName = "Workspace_URL_"
					+ info.getWorkspaceType().toString();
			IWorkspace adoWorkspace = (IWorkspace) (objectFactory.getBean(
					objName, new Object[] { info }));
			return adoWorkspace;
		}
	}
}